package com.dmall.chapter03.section04;

/**
 * 使用快慢指针的方式
 * 时间复杂度：O(n)
 * 空间复杂度：O(1)
 * @author xiao1.wang
 * @date 2020-12-02 12:12:28
 */
public class Leetcode141V2 {

    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head.next;
        ListNode fast = head.next.next;
        while (fast != null && fast.next != null) {
            if (slow == fast) {
                return true;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return false;
    }

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
